$(function() {
    //从缓存中获取数据（在登录成功后会将当前用户和用户令牌放入缓存中）
    const user = JSON.parse(window.sessionStorage.getItem("user"));
    const token = window.sessionStorage.getItem("token");
    if(user == null || token == null){
        alert("请先登录");
        window.location.href = "../html/welcome.html";
    }

    //初始化时的第一次请求 渲染第一页未审核的鸡汤数据
    heartPageAjax(token,1);
    //初始化时的第一次请求 渲染第一页已审核的鸡汤数据
    againHeartPageAjax(token,1);

    //为底部分页框添加分页方法 初次审核
    $("#heartPageSelect").change(function(){
        heartPageAjax(token,$(this).children('option:selected').val());
    })
    //为底部分页框添加分页方法 二次审核
    $("#againHeartPageSelect").change(function(){
        againHeartPageAjax(token,$(this).children('option:selected').val());
    })

    //为审核按钮添加点击事件
    for (let i = 1; i <= 10; i++) {
        $("#heartVerifyBtn" + i).click(function (){
            const heartId = $("#heartNum" + i).text();
            getHeartByIdAjax(token,heartId);
        });
        $("#againHeartVerifyBtn" + i).click(function (){
            const heartId = $("#againHeartNum" + i).text();
            getHeartByIdAjax(token,heartId);
        });
    }

    //为审核通过和审核未通过按钮添加点击事件
    $("#heartVerifyTrueBtn").click(function (){
        const heartId = $("#heartId").text();
        verifyHeartAjax(token,heartId,"true");
    });
    $("#heartVerifyFalseBtn").click(function (){
        const heartId = $("#heartId").text();
        verifyHeartAjax(token,heartId,"false");
    });

    //关闭页面时调用logout方法，退出当前登录用户
    $(window).unload(function(){
        $.ajax({
            type:"POST",
            contentType:"application/json",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            url :"http://localhost:2082/logout?username=" + user.username
        })
    });

});


//未审核鸡汤数据分页ajax
function heartPageAjax(token,current) {
    $.ajax({
        type: "GET",
        contentType: "application/json",
        headers: {
            "token":token
        },
        url: "http://localhost:2082/heart/page?verify=0&current=" + current,
        success: function(data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const token = xhr.getResponseHeader("token");
            if(token == "overdue"){
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    const pageData = result.data;
                    //records：获取到的分页数组数据
                    const records = eval("("+JSON.stringify(pageData)+")").records;
                    //total：所有数据的数量
                    const total = eval("("+JSON.stringify(pageData)+")").total;
                    //size：每页数据的数量
                    const size = eval("("+JSON.stringify(pageData)+")").size;
                    //current：当前页数
                    const current = eval("("+JSON.stringify(pageData)+")").current;
                    //总页数
                    const pageNum = eval("("+JSON.stringify(pageData)+")").pages;

                    //初始化底部分页框
                    $("#heartTotalPage").empty();
                    $("#heartTotalPage").html(pageNum);
                    $("#heartPageSelect").empty();
                    for (let i = 0; i < pageNum; i++) {
                        const pageValue = i + 1;
                        if(current === pageValue){
                            $("#heartPageSelect").append("<option value='"+pageValue+"' selected>"+pageValue+"</option>");
                        }else {
                            $("#heartPageSelect").append("<option value='"+pageValue+"'>"+pageValue+"</option>");
                        }
                    }

                    //先清空数据
                    for (let i = 1; i <= 10; i++) {
                        $("#heartNum" + i).empty();
                        $("#heartAuthor" + i).empty();
                        $("#heartPlace" + i).empty();
                    }
                    //再进行赋值
                    let heartNum;
                    if( (total-size*(current-1)) >= 10){
                        heartNum = 10;
                    }else if( (total-size*(current-1)) < 10){
                        heartNum = total-size*(current-1);
                        for (let i = heartNum + 1; i <= 10; i++) {
                            //添加不可见样式
                            $("#heartRow" + i).attr("style","display:none");
                        }
                    }
                    for (let i = 1; i <= heartNum; i++) {
                        //移除不可见样式
                        $("#heartRow" + i).removeAttr("style");
                        let heartId = JSON.stringify(records[i-1].id);
                        let username = JSON.stringify(records[i-1].username);
                        let place = JSON.stringify(records[i-1].place);
                        if(heartId == null){
                            heartId = "/";
                        }
                        if(username == null){
                            username = "/";
                        }
                        if(place == null){
                            place = "/";
                        }

                        $("#heartNum" + i).html(heartId.replace(/\"/g, ""));
                        $("#heartAuthor" + i).html(username.replace(/\"/g, ""));
                        $("#heartPlace" + i).html(place.replace(/\"/g, ""));
                    }
                }
                //操作失败
                else if(result.code == 500){
                    $('#add').modal('hide');
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//已审核鸡汤数据分页ajax
function againHeartPageAjax(token,current) {
    $.ajax({
        type: "GET",
        contentType: "application/json",
        headers: {
            "token":token
        },
        url: "http://localhost:2082/heart/page?getVerified=true&current=" + current,
        success: function(data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const token = xhr.getResponseHeader("token");
            if(token == "overdue"){
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    const pageData = result.data;
                    //records：获取到的分页数组数据
                    const records = eval("("+JSON.stringify(pageData)+")").records;
                    //total：所有数据的数量
                    const total = eval("("+JSON.stringify(pageData)+")").total;
                    //size：每页数据的数量
                    const size = eval("("+JSON.stringify(pageData)+")").size;
                    //current：当前页数
                    const current = eval("("+JSON.stringify(pageData)+")").current;
                    //总页数
                    const pageNum = eval("("+JSON.stringify(pageData)+")").pages;

                    //初始化底部分页框
                    $("#againHeartTotalPage").empty();
                    $("#againHeartTotalPage").html(pageNum);
                    $("#againHeartPageSelect").empty();
                    for (let i = 0; i < pageNum; i++) {
                        const pageValue = i + 1;
                        if(current === pageValue){
                            $("#againHeartPageSelect").append("<option value='"+pageValue+"' selected>"+pageValue+"</option>");
                        }else {
                            $("#againHeartPageSelect").append("<option value='"+pageValue+"'>"+pageValue+"</option>");
                        }
                    }

                    //先清空数据
                    for (let i = 1; i <= 10; i++) {
                        $("#againHeartNum" + i).empty();
                        $("#againHeartAuthor" + i).empty();
                        $("#againHeartPlace" + i).empty();
                        $("#heartVerifyResult" + i).empty();
                    }
                    //再进行赋值
                    let heartNum;
                    if( (total-size*(current-1)) >= 10){
                        heartNum = 10;
                    }else if( (total-size*(current-1)) < 10){
                        heartNum = total-size*(current-1);
                        for (let i = heartNum + 1; i <= 10; i++) {
                            //添加不可见样式
                            $("#againHeartRow" + i).attr("style","display:none");
                        }
                    }
                    for (let i = 1; i <= heartNum; i++) {
                        //移除不可见样式
                        $("#againHeartRow" + i).removeAttr("style");
                        let heartId = JSON.stringify(records[i-1].id);
                        let username = JSON.stringify(records[i-1].username);
                        let place = JSON.stringify(records[i-1].place);
                        let verify = JSON.stringify(records[i-1].verify);
                        if(heartId == null){
                            heartId = "/";
                        }
                        if(username == null){
                            username = "/";
                        }
                        if(place == null){
                            place = "/";
                        }
                        if(verify == null){
                            verify = "/";
                        }else if(verify == 1){
                            verify = "通过";
                        }else if(verify == 2){
                            verify = "未通过";
                        }

                        $("#againHeartNum" + i).html(heartId.replace(/\"/g, ""));
                        $("#againHeartAuthor" + i).html(username.replace(/\"/g, ""));
                        $("#againHeartPlace" + i).html(place.replace(/\"/g, ""));
                        $("#heartVerifyResult" + i).html(verify.replace(/\"/g, ""));
                    }
                }
                //操作失败
                else if(result.code == 500){
                    $('#add').modal('hide');
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//获取其中一条鸡汤数据ajax
function getHeartByIdAjax(token,heartId){
    $.ajax({
        type: "GET",
        contentType: "application/json",
        headers: {
            "token":token
        },
        url: "http://localhost:2082/heart/one?heartId=" + heartId,
        success: function(data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const token = xhr.getResponseHeader("token");
            if(token == "overdue"){
                $('#addTucao').modal('hide');
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    const heartData = result.data;
                    const username = eval("("+JSON.stringify(heartData)+")").username;
                    const createTime = eval("("+JSON.stringify(heartData)+")").createTime;
                    const place = eval("("+JSON.stringify(heartData)+")").place;
                    const heartId = eval("("+JSON.stringify(heartData)+")").id;
                    const content = eval("("+JSON.stringify(heartData)+")").content;

                    //先清空数据
                    $("#heartUsername").empty();
                    $("#heartTime").empty();
                    $("#heartPlace").empty();
                    $("#heartId").empty();
                    $("#heartContent").empty();
                    //再进行赋值
                    $("#heartUsername").html(username);
                    $("#heartTime").html(createTime);
                    $("#heartPlace").html(place);
                    $("#heartId").html(heartId);
                    $("#heartContent").html(content);
                }
                //操作失败
                else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//对一条鸡汤进行审核ajax
function verifyHeartAjax(token,heartId,verify){
    $.ajax({
        type: "PUT",
        contentType: "application/json",
        headers: {
            "token":token
        },
        url: "http://localhost:2082/heart/verify?heartId=" + heartId +"&verify=" + verify,
        success: function(data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if(responseToken == "overdue"){
                $('#addTucao').modal('hide');
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                if(result.code == 200){
                    $("#heartVerifySource").modal('hide');
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "success",
                        autoclose: 2000
                    });
                    //再进行一次分页显示操作
                    const current = $("#heartPageSelect option:selected").text();
                    heartPageAjax(token,current);
                    const againCurrent = $("#againHeartPageSelect option:selected").text();
                    againHeartPageAjax(token,againCurrent);
                }
                //操作失败
                else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}



